import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';

import '../../common/index.dart';

class SquarePage extends ConsumerStatefulWidget {
  const SquarePage({super.key});

  @override
  ConsumerState<SquarePage> createState() => _SquarePageState();
}

class _SquarePageState extends ConsumerState<SquarePage>
    with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // 页面初始化时加载所有分享数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadAllShares();
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台返回前台时，刷新用户状态
    if (state == AppLifecycleState.resumed) {
      ref.read(userProvider.notifier).reloadCurrentUser();
    }
  }

  /// 加载所有用户的分享
  Future<void> _loadAllShares() async {
    final shareNotifier = ref.read(shareProvider.notifier);
    // 加载所有分享数据
    await shareNotifier.loadAllShares();
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);
    final shareState = ref.watch(shareProvider);

    return Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.squareBg),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          top: false,
          bottom: false,
          child: Column(
            children: [
              // 顶部用户信息和分享按钮
              _buildTopSection(currentUser),

              SizedBox(height: 12.h),

              // 社区分享列表
              Expanded(child: _buildSharesList(shareState)),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部用户信息和聊天按钮
  Widget _buildTopSection(UserEntity? currentUser) {
    return Container(
      padding: EdgeInsets.only(top: 55.h, left: 12.w, right: 12.w),
      child: Row(
        children: [
          // 当前用户头像
          if (currentUser != null)
            UserAvatarSquare(
              size: 48.w,
              avatarPath: currentUser.avatar,
              fallbackAsset: MyImages.kina,
              borderRadius: 10.r,
            ),
          if (currentUser == null)
            Icon(
              Icons.person,
              size: 48.w,
              color: Colors.white.withValues(alpha: 0.7),
            ),

          Spacer(),

          // 聊天按钮
          GestureDetector(
            onTap: () {
              AppRouterExtension(context).navigateTo(AppRoutes.messageList);
            },
            child: SvgPicture.asset(MyIcons.chat, width: 36.w, height: 36.h),
          ),
        ],
      ),
    );
  }

  /// 构建分享列表
  Widget _buildSharesList(ShareState shareState) {
    if (shareState.isLoading) {
      return const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
        ),
      );
    }

    if (shareState.error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              shareState.error!,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontFamily: 'Pangram',
              ),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 16.h),
            ElevatedButton(
              onPressed: _loadAllShares,
              child: const Text('again'),
            ),
          ],
        ),
      );
    }

    if (shareState.shares.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.forum_outlined,
              size: 64.w,
              color: Colors.white.withValues(alpha: 0.5),
            ),
            SizedBox(height: 16.h),
            Text(
              'no shares',
              style: TextStyle(
                color: Colors.white.withValues(alpha: 0.8),
                fontSize: 16.sp,
                fontFamily: 'Pangram',
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              'be the first to share',
              style: TextStyle(
                color: Colors.white.withValues(alpha: 0.6),
                fontSize: 14.sp,
                fontFamily: 'Pangram',
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: () async {
        await _loadAllShares();
      },
      child: ListView.builder(
        padding: EdgeInsets.only(
          left: 10.w,
          right: 10.w,
          top: 16.h,
          bottom: 75.h,
        ),
        itemCount: shareState.shares.length,
        itemBuilder: (context, index) {
          final share = shareState.shares[index];
          return GestureDetector(
            onTap: () async {
              // 增加浏览量
              await ref
                  .read(shareProvider.notifier)
                  .incrementViewCount(share.id);

              AppRouterExtension(context).navigateTo(
                AppRoutes.shareDetail,
                params: {'shareId': share.id},
              );
            },
            child: ShareItem(share: share, isSquare: true),
          );
        },
      ),
    );
  }
}
